from django.db.models import F
from django.shortcuts import redirect

from ..models import UserInfo, Permission, Role
from django.conf import settings


def init_permission(request, user_obj):
    """
    初始化用户权限，写入session，方便后续使用
    :param request:
    :param user_obj:
    :return:
    """
    roles = user_obj.roles.all()
    permissions_item_list = user_obj.roles.values(
        'permissions__id',
        'permissions__name',
        'permissions__url_name',
        'permissions__method',
        'permissions__sort',
        'permissions__is_menu',
        'permissions__parent',
    ).distinct()
    # 权限url列表，用于中间件验证用户权限
    permissions_url_list = []
    # 权限菜单列表，只包含当做菜单的接口
    permissions_menu_list = []
    for item in permissions_item_list:
        item_dict = {
            "id": item['permissions__id'],
            "name": item['permissions__name'],
            "url": item['permissions__url_name'],
            "method": item['permissions__method'],
            "is_menu": item['permissions__is_menu'],
            "sort": item['permissions__sort'],
            "parent_id": item['permissions__parent']
        }
        permissions_url_list.append(item_dict)
        if item['permissions__is_menu']:
            permissions_menu_list.append(item_dict)

    if len(roles) == 1 and roles.values()[0]['id'] == 0 and roles.values()[0]['name'] == '超级管理员':
        permissions_menu_list = list(Permission.objects.filter(is_menu=True).values('id','name','method','is_menu','sort', 'parent_id', url=F('url_name')))
        print('超级管理员')
    # 权限url列表
    request.session[settings.SESSION_PERMISSION_URL_KEY] = permissions_url_list
    # 权限菜单列表
    request.session[settings.SESSION_MENU_KEY] = permissions_menu_list
    # 登录标识
    request.session['is_login'] = True
    # 将登录用户存储到session 方便后续调用
    request.session['username'] = user_obj.username
    print('permissions_menu_list: %s' % permissions_menu_list)
    print('permissions_url_list: %s' % permissions_url_list)
